package com.bike.modules.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bike.common.Const;
import com.bike.common.Res;
import com.bike.common.utils.UserUtils;
import com.bike.modules.dao.InfoMapper;
import com.bike.modules.dao.ParkMapper;
import com.bike.modules.dto.CreateOrderDTO;
import com.bike.modules.dto.OrderReturnDTO;
import com.bike.modules.dto.QueryDTO;
import com.bike.modules.entity.Info;
import com.bike.modules.entity.Park;
import org.gavaghan.geodesy.GlobalCoordinates;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bike.modules.dao.OrderMapper;
import com.bike.modules.entity.Order;
import com.bike.modules.service.OrderService;
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService{

    @Autowired
    private InfoMapper infoMapper;
    @Autowired
    private ParkMapper parkMapper;

    @Override
    public IPage<OrderReturnDTO> selectPage(QueryDTO dto) {
        IPage<Object> page = new Page<>(dto.getCurrent(),dto.getSize());
        return this.baseMapper.selectPage(page,dto);
    }

    @Override
    public Res<String> createOrder(CreateOrderDTO dto) {
        Info info = infoMapper.selectByBikeNo(dto.getBikeNo());
        if(info == null){
            return Res.errorMsg("该单车不存在");
        }
        GlobalCoordinates source = new GlobalCoordinates(Double.parseDouble(dto.getUserLat()), Double.parseDouble(dto.getUserLng()));
        GlobalCoordinates target = new GlobalCoordinates(info.getStopLat().doubleValue(), info.getStopLng().doubleValue());
        double distance =  Const.getDistanceMeter(source, target);
        // 判断自己的位置与单车的距离，超过20就无法使用
        if(distance > 20){
            return Res.errorMsg("你与该单车位置超过20米，无法使用");
        }
        int result = this.baseMapper.insert(Order.builder()
                .orderNo(Const.generateOrderNo())
                .bikeNo(dto.getBikeNo())
                .startLng(info.getStopLng())
                .startLat(info.getStopLat())
                .starParkId(info.getParkId())
                .userId(UserUtils.getUserId())
                .build());
        if(result != 1){
            return Res.errorMsg("用车失败");
        }
        info.setStatus("2");
        infoMapper.updateById(info);
        return Res.successMsg("用车成功");
    }

    @Override
    public Res<String> returnBike(CreateOrderDTO dto) {
        IPage<Object> page = new Page<>(1,1000);
        List<Park> parkList = parkMapper.selectPage(page, new QueryDTO()).getRecords();
        //当前位置
        GlobalCoordinates source = new GlobalCoordinates(Double.parseDouble(dto.getUserLat()), Double.parseDouble(dto.getUserLng()));
        Park resultPark = null;
        for(Park park : parkList){
            GlobalCoordinates target = new GlobalCoordinates(park.getCenterLat().doubleValue(), park.getCenterLng().doubleValue());
            double distance =  Const.getDistanceMeter(source, target);
            //在停车点范围内
            if(distance < park.getParkRange()){
                resultPark = park;
                break;
            }
        }
        if(resultPark == null){
            return Res.errorMsg("未在停车点范围内");
        }
        //修改订单
        Order order = this.baseMapper.selectById(dto.getOrderId());
        order.setStatus(1);
        order.setEndLat(new BigDecimal(dto.getUserLat()));
        order.setEndLng(new BigDecimal(dto.getUserLng()));
        order.setEndParkId(resultPark.getId());
        long currentTime =System.currentTimeMillis();
        long result = (currentTime - order.getCreateTime().getTime())/1000/60;
        order.setTime((int) result);
        //行驶距离
        GlobalCoordinates target = new GlobalCoordinates(order.getStartLat().doubleValue(), order.getStartLng().doubleValue());
        double distance =  Const.getDistanceMeter(source, target);
        order.setMileage(new BigDecimal(distance));
        this.baseMapper.updateById(order);

        //修改单车信息
        Info info = infoMapper.selectByBikeNo(dto.getBikeNo());
        if(info == null){
            return Res.errorMsg("该单车不存在");
        }
        info.setStatus("1");
        info.setStopLat(new BigDecimal(dto.getUserLat()));
        info.setStopLng(new BigDecimal(dto.getUserLng()));
        info.setUsageCount(info.getUsageCount()+1);
        info.setUsageTime(info.getUsageTime()+(int) result);
        info.setUsageMileage(info.getUsageMileage().add(new BigDecimal(distance/1000)));
        infoMapper.updateById(info);
        return Res.successMsg("还车成功");
    }

    public static void main(String[] args) throws InterruptedException {
        long currentTime =System.currentTimeMillis();
        Thread.sleep(3000);
        long currentTime2 =System.currentTimeMillis();
        long result = (currentTime2 - currentTime)/1000;
        System.out.println(result);
    }
}
